package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.SkuFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private SkuFeignService skuFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Override
    public CartItem addCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> boundHashOps = getCartOps();

        String json= (String) boundHashOps.get(skuId.toString());
        if (StringUtils.isEmpty(json)){
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> {
                R r = skuFeignService.info(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setSkuId(skuId);
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
            }, executor);

            CompletableFuture<Void> f2 = CompletableFuture.runAsync(() -> {
                List<String> skuAttrListToString = skuFeignService.getSkuAttrListToString(skuId);
                cartItem.setSkuAttr(skuAttrListToString);
            }, executor);

            CompletableFuture.allOf(f1,f2).get();


            String cartItemJson = JSON.toJSONString(cartItem);
            boundHashOps.put(Long.toString(skuId),cartItemJson);


            return cartItem;
        }else {
            CartItem cartItem = JSON.parseObject(json, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            String s = JSON.toJSONString(cartItem);
            boundHashOps.put(skuId.toString(),s);
            return cartItem;

        }


    }

    @Override
    public CartItem getCartItemBySkuId(String skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String cartItemJson = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(cartItemJson, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Long userId = userInfoTo.getUserId();
        if (userId!=null){
            //已经登陆
            //查看临时购物车有没有商品
            String tempCartKey="gulimall:cart:"+userInfoTo.getUserKey();
            List<CartItem> tempCartItem = getCartItems(tempCartKey);
            if (tempCartItem!=null && tempCartItem.size()>0){
                //临时购物车有东西
                for (CartItem item : tempCartItem) {
                    //已登录，直接加入到已登录购物车
                    addCart(item.getSkuId(),item.getCount());
                }
                //删除临时购物车
                deleteCart(tempCartKey);
            }
            String cartKey="gulimall:cart:"+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            Cart cart = new Cart();
            cart.setCartItems(cartItems);
            return cart;

        }else {
//            没登陆
            String cartKey="gulimall:cart:"+userInfoTo.getUserKey();
            List<CartItem> cartItem = getCartItems(cartKey);
            Cart cart = new Cart();
            cart.setCartItems(cartItem);
            return cart;
        }

    }

    @Override
    public void deleteCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(String skuId, Integer check) {
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCheck(check==1?true:false);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void countItem(String skuId, Integer num) {
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(String skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId);
    }

    @Override
    public List<CartItem> getCheckedCart() {
        //获取当前用户的购物车 当前用户信息在此线程里
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            String cartKey="gulimall:cart:"+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream().filter(item -> item.getCheck()).map(cartItem -> {
                //设置最新的价格 通过远程调用查价格
                Long skuId = cartItem.getSkuId();
                cartItem.setPrice(skuFeignService.getPrice(skuId));
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Long userId = userInfoTo.getUserId();
        String pre="";
        if (userId!=null){
            pre="gulimall:cart:"+userInfoTo.getUserId();
        }else {
            pre="gulimall:cart:"+userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(pre);
        return boundHashOps;
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = cartOps.values();
        if (values!=null && values.size()>0){

            List<CartItem> cartItems = values.stream().map((obj) -> {
                String json = (String) obj;
                CartItem cartItem = JSON.parseObject(json, CartItem.class);

                return cartItem;
            }).collect(Collectors.toList());
            return cartItems;
        }
        return null;
    }
}
